package me.tuyou.activiti;

import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.junit.Before;

import java.text.SimpleDateFormat;
import java.util.List;

public class Base {

    protected ProcessEngine processEngine;

    protected IdentityService identityService;
    protected RuntimeService runtimeService;
    protected RepositoryService repositoryService;
    protected HistoryService historyService;
    protected FormService formService;
    protected TaskService taskService;

    //创建表
    @Before
    public void creatTable() {
        processEngine = ProcessEngineConfiguration
                .createProcessEngineConfigurationFromResource("activiti.cfg.xml")
                .buildProcessEngine();
        identityService = processEngine.getIdentityService();
        runtimeService = processEngine.getRuntimeService();
        repositoryService = processEngine.getRepositoryService();
        historyService = processEngine.getHistoryService();
        formService = processEngine.getFormService();
        taskService = processEngine.getTaskService();


    }

    /**
     * 打印流程进度
     */
    public void printProcessProgress(String processInstanceId) {
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceEndTime()
                .asc()
                .list();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
        for (HistoricTaskInstance instance : list) {
            System.out.println(ReflectionToStringBuilder.toString(instance));
        }
    }

    /**
     * 验证流程是否结束
     */
    public void checkProcessStop(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (processInstance == null) {
            System.out.println("流程已经结束");
        } else {
            System.out.println("流程正在进行中");
        }
    }
}
